import json
import random
import re

from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse, HttpResponse
from django.views import View
from django_redis import get_redis_connection

from AiJiaHome.libs.captcha.captcha import captcha
from AiJiaHome.utils.response_code import RET
from verifications import constants
import logging

logger = logging.getLogger('django')


class SMSCodeView(View):
    '''短信验证码'''

    def post(self, request):
        '''
        短信验证码请求
        '''
        # 接受参数
        json_data = request.body.decode()
        json_dict = json.loads(json_data)
        mobile = json_dict.get('mobile')
        image_code_client = json_dict.get('image_code')
        cur_uuid = json_dict.get('image_code_id')

        # 校验参数
        if not all([mobile, image_code_client, cur_uuid]):
            return JsonResponse({'errno': RET.NODATA, 'errmsg': "缺少必传参数"})

        if not re.match(r'^[1][34578][0-9]{9}$', mobile):
            return JsonResponse({'errno': RET.NODATA, 'errmsg': "手机号格式错误"})

        # 3.创建连接对象
        redis_conn = get_redis_connection('verify_code')

        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'errno': RET.REQERR,
                                 'errmsg': '发送短信过于频繁'})

        # 4.提取图形验证码
        image_code_server = redis_conn.get('img_%s' % cur_uuid)
        if image_code_server is None:
            return JsonResponse({'errno': RET.PARAMERR,
                                 'errmsg': '图形验证码失效'})

        # 5.删除验证码,避免恶意测试
        try:
            redis_conn.delete('img_%s' % cur_uuid)
        except Exception as e:
            logger.error(e)

        # 6.对比图形验证码
        image_code_server = image_code_server.decode('utf-8')

        if image_code_server.lower() != image_code_client.lower():
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '图形验证码错误'})

        # 7.生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        logger.info(sms_code)

        # 运用redis管道
        pl = redis_conn.pipeline()

        # 8.保存短信验证码
        pl.setex('sms_code_%s' % mobile,
                 constants.SMS_CODE_REDIS_EXPIRES,
                 sms_code)

        pl.setex('send_flag_%s' % mobile,
                 constants.SEND_SMS_CODE_INTERVAL,
                 1)

        # 统一请求redis数据库
        pl.execute()
        # 9.发送短信
        # ccp_send_sms_code.delay(mobile, sms_code)
        # CCP().send_template_sms(mobile, [sms_code, 5],
        #                         constants.SENT_SMS_CODE_TEMPLATE_ID)

        # 10.响应结果
        return JsonResponse({'errno': RET.OK, 'errmsg': "短信发送成功"})


class ImageCodeView(View):
    '''图形验证码'''

    def get(self, request):
        # 当前图片验证码UUID
        cur_uuid = request.GET.get('cur')
        # 上一次图片验证码UUID
        pre_uuid = request.GET.get('pre')

        if not all([cur_uuid, pre_uuid]):
            return JsonResponse({"errno": RET.DATAERR, "errmsg": "缺少必传参数"})

        # 生成验证码图片
        text, image = captcha.generate_captcha()

        # 保存验证码图片
        redis_conn = get_redis_connection('verify_code')

        # 验证码有效期,单位秒
        # IMAGE_CODE_REDIS_EXPIRES = 300
        redis_conn.setex('img_%s' % cur_uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        redis_conn.delete('img_%s' % pre_uuid)

        # 响应图片验证码
        return HttpResponse(image, content_type='image/jpg')
